package com.ysf.cn.springbootshrio.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

//import javax.security.auth.Subject;

/**
 * @author ysf
 * @date 2020/2/13 14:52
 */
@Controller
public class LoginController {

    /**
     * Get请求,登陆页面跳转
     * @return
     */
    @GetMapping("/login")
    public String login(){
        //如果认证通过,直接跳转到首页
        if(SecurityUtils.getSubject().isAuthenticated()){
            return "admin/index";
        }
        return "admin/login";
    }

    /**
     * 提交表单登陆
     * @param username
     * @param password
     * @param model
     * @return
     */
    @ApiOperation("提交表单登陆")
    @PostMapping(value = "/login")
    public Object login(@ApiParam("用户名") String username, @ApiParam("密码")String password, @ApiParam("model")Model model){
        Subject user=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try {
            //shiro帮我们匹配密码什么的,我们只需要把东西传给它,它会根据我们在UserRealm里认证方法设置的来验证
            user.login(token);
            return  "admin/index";
        }catch (UnknownAccountException e){
            //账号不存在和下面密码错误一般都合并一个账号或密码错误,这样可以增加暴力破解难度
            model.addAttribute("message","账号不存在");
        }catch (DisabledAccountException e){
            model.addAttribute("message","账号为启用！");
        }catch (IncorrectCredentialsException e){
            model.addAttribute("message","密码错误！");
        }catch (Throwable e){
            model.addAttribute("message","未知错误");
        }
        return "admin/login";
    }

    /**
     * 退出
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "admin/login";
    }




}
